﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;


namespace CodePlexNewReleaseChecker
{
    public class ReleasedStripper : IReleaseNamesProvider
    {
        private static readonly string _basicDownloadsURL = "http://{0}.codeplex.com/releases/";
        private static readonly string _regex = "<td class=\"ReleaseCell\">.*?<a.*?href=\"(?<releseLink>.*?)\".*?>(?<releaseName>.*?)</a>.*?</td>";
        private static readonly string _regexCurrentLink = "<a.*?class=\"downloads_active\" href=\"(?<releaseLink>.*?)\">downloads</a>";
        private static readonly string _regexCurrentName = "<h1 class=\"page_title\">(?<releaseName>.*?)</h1>";
        //Regex nameReg = new Regex(".*?: (?<releaseName>.*?) \\(.*?\\)");
        
        public List<BareRelease> GetReleaseNames(string projectName)
        {
            string getURL = string.Format(_basicDownloadsURL, projectName);
            WebClient client = new WebClient();
            string feed = client.DownloadString(getURL);

            //This regex gets all releases EXCEPT the one we are looking at
            Regex nameReg = new Regex(_regex, RegexOptions.Singleline | RegexOptions.ExplicitCapture);
            var matches = nameReg.Matches(feed);

            List<BareRelease> releases = (from Match c in matches
                    select new BareRelease()
                    {
                        Name = c.Groups["releaseName"].Value,
                        Link = c.Groups["releaseLink"].Value
                    }).ToList();

            //get the current release
            BareRelease brMain = new BareRelease();
            Match mName = Regex.Match(feed, _regexCurrentName);
            Match mLink = Regex.Match(feed, _regexCurrentLink);

            brMain.Name = mName.Groups["releaseName"].Value;
            brMain.Link = mLink.Groups["releaseLink"].Value;

            releases.Add(brMain);

            return releases;
        }
    }
}
